<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>登录</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="login-container">
        <!-- Logo 区域 -->
        <div class="logo-section">
          <ion-icon :icon="homeOutline" size="large" color="primary"></ion-icon>
          <h1>租房系统</h1>
          <p>欢迎使用租房管理系统</p>
        </div>

        <!-- 登录表单 -->
        <form @submit.prevent="handleLogin" class="login-form">
          <ion-item>
            <ion-label position="stacked">用户名</ion-label>
            <ion-input
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <ion-item>
            <ion-label position="stacked">密码</ion-label>
            <ion-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :disabled="loading"
              required
            ></ion-input>
          </ion-item>

          <ion-button
            expand="block"
            type="submit"
            :disabled="loading || !isFormValid"
            class="login-button"
          >
            <ion-spinner v-if="loading" name="crescent"></ion-spinner>
            <span v-else>登录</span>
          </ion-button>
        </form>

        <!-- 注册链接 -->
        <div class="register-link">
          <p>还没有账户？ <ion-button fill="clear" @click="goToRegister">立即注册</ion-button></p>
        </div>

        <!-- 测试账号提示 -->
        <div class="test-accounts">
          <h3>测试账号</h3>
          <div class="account-list">
            <div class="account-item" @click="fillAccount('admin', '123456')">
              <strong>管理员:</strong> admin / 123456
            </div>
            <div class="account-item" @click="fillAccount('landlord1', '123456')">
              <strong>房东:</strong> landlord1 / 123456
            </div>
            <div class="account-item" @click="fillAccount('tenant1', '123456')">
              <strong>租客:</strong> tenant1 / 123456
            </div>
            <div class="account-item" @click="fillAccount('user1', '123456')">
              <strong>普通用户:</strong> user1 / 123456
            </div>
          </div>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonItem,
  IonLabel,
  IonInput,
  IonButton,
  IonIcon,
  IonSpinner,
  alertController,
  toastController
} from '@ionic/vue'
import { homeOutline } from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { login } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const loginForm = ref({
  username: '',
  password: ''
})

const loading = ref(false)

// 表单验证
const isFormValid = computed(() => {
  return loginForm.value.username.trim() !== '' && loginForm.value.password.trim() !== ''
})

// 填充测试账号
const fillAccount = (username: string, password: string) => {
  loginForm.value.username = username
  loginForm.value.password = password
}

// 跳转到注册页
const goToRegister = () => {
  router.push('/register')
}

// 处理登录
const handleLogin = async () => {
  if (!isFormValid.value) return

  loading.value = true

  try {
    const response = await login({
      username: loginForm.value.username.trim(),
      password: loginForm.value.password.trim()
    })

    if (response.success && response.data) {
      // 保存用户信息到 store
      userStore.login(response.data.user, response.data.token)

      // 显示成功提示
      const toast = await toastController.create({
        message: '登录成功！',
        duration: 2000,
        color: 'success',
        position: 'top'
      })
      await toast.present()

      // 根据用户状态决定跳转
      const user = response.data.user
      if (user.hasSetRoles && user.roles && user.roles.length > 0) {
        // 已设置角色的用户，设置当前角色并跳转到主页
        userStore.setCurrentRole(user.roles[0])
        router.replace('/tabs/home')
      } else {
        // 未设置角色的用户，跳转到角色选择页面
        router.replace('/role-select')
      }
    } else {
      throw new Error(response.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    
    const alert = await alertController.create({
      header: '登录失败',
      message: error.message || '用户名或密码错误',
      buttons: ['确定']
    })
    await alert.present()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.logo-section {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px 0;
}

.logo-section h1 {
  margin: 16px 0 8px 0;
  color: var(--ion-color-primary);
  font-weight: bold;
}

.logo-section p {
  color: var(--ion-color-medium);
  margin: 0;
}

.login-form {
  margin-bottom: 30px;
}

.login-form ion-item {
  margin-bottom: 16px;
}

.login-button {
  margin-top: 20px;
  height: 48px;
}

.register-link {
  text-align: center;
  margin: 20px 0;
}

.register-link p {
  color: var(--ion-color-medium);
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.register-link ion-button {
  --color: var(--ion-color-primary);
  font-weight: 600;
  margin: 0;
  height: auto;
  --padding-start: 4px;
  --padding-end: 4px;
}

.test-accounts {
  background: var(--ion-color-light);
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.test-accounts h3 {
  margin: 0 0 12px 0;
  color: var(--ion-color-dark);
  font-size: 14px;
  text-align: center;
}

.account-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.account-item {
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 12px;
}

.account-item:hover {
  background: var(--ion-color-primary-tint);
}

.account-item strong {
  color: var(--ion-color-primary);
}
</style>
